﻿@{
    ViewData["Title"] = "修改生产退料";
    Layout = null;
}
@Html.AntiForgeryToken()
@using Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" id="updateForm" lay-filter="updateForm">
                <div class="layui-form-item">
                    <label class="layui-form-label required">退料单编号</label>
                    <div class="layui-input-inline" style="width:300px;">
                        <input type="text" name="ReturnOrderCode" id="returnOrderCodeInput" placeholder="请输入退料单编号" autocomplete="off" class="layui-input" lay-verify="required" lay-reqtext="退料单编号不能为空">
                    </div>
                    <div class="layui-input-inline" style="width:120px;">
                        <input type="checkbox" name="AutoGenerate" id="autoGenerateReturnOrderCode" lay-skin="switch" lay-filter="autoGenerateReturnOrderCode" lay-text="自动生成|手动输入">
                    </div>
                    <label class="layui-form-label required">退料单名称</label>
                    <div class="layui-input-inline" style="width:300px;">
                        <input type="text" name="ReturnOrderName" placeholder="请输入退料单名称" autocomplete="off" class="layui-input" lay-verify="required" lay-reqtext="退料单名称不能为空">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">生产工单</label>
                    <div class="layui-input-inline" style="width:300px;">
                        <input type="text" name="ProductionWorkOrder" id="ProductionWorkOrder" placeholder="请输入生产工单" autocomplete="off" class="layui-input" lay-verify="required" lay-reqtext="生产工单不能为空">
                    </div>
                    <div class="layui-input-inline" style="width:40px;">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="searchWorkOrder"><i class="layui-icon layui-icon-search"></i></button>
                    </div>
                    <label class="layui-form-label required">接收仓库</label>
                    <div class="layui-input-inline" style="width:300px;">
                        <select name="ReceiveWarehouse" lay-verify="required" lay-search lay-reqtext="接收仓库不能为空">
                            <option value="">请选择</option>
                            <option value="仓库A">仓库A</option>
                            <option value="仓库B">仓库B</option>
                        </select>
                    </div>
                    <label class="layui-form-label required">退料日期</label>
                    <div class="layui-input-inline" style="width:200px;">
                        <input type="text" name="ReturnDate" id="ReturnDate" placeholder="请选择日期" autocomplete="off" class="layui-input" lay-verify="required" lay-reqtext="退料日期不能为空">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <textarea name="Remark" placeholder="请输入内容" class="layui-textarea" style="min-height:80px;"></textarea>
                    </div>
                </div>
                <div class="layui-form-item" style="text-align:right;">
                    <button class="layui-btn" lay-submit lay-filter="saveBtn">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 工单选择弹窗模板 -->
<script type="text/html" id="workOrderDialogTpl">
    <div style="padding:20px;">
        <form class="layui-form" id="workOrderSearchForm" style="margin-bottom:10px;">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <input type="text" name="orderName" placeholder="工单名称" class="layui-input" style="width:150px;">
                </div>
                <div class="layui-inline">
                    <input type="text" name="productCode" placeholder="产品编号" class="layui-input" style="width:150px;">
                </div>
                <div class="layui-inline">
                    <button class="layui-btn" lay-submit lay-filter="workOrderSearchBtn">搜索</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
        <table id="workOrderTable" lay-filter="workOrderTable"></table>
        <div style="text-align:right;margin-top:10px;">
            <button class="layui-btn" id="selectWorkOrderBtn">确定</button>
            <button class="layui-btn layui-btn-primary" id="closeWorkOrderDialog">取消</button>
        </div>
    </div>
</script>

<script>
layui.use(['form', 'laydate', 'layer', 'table'], function(){
    var form = layui.form,
        laydate = layui.laydate,
        layer = layui.layer,
        table = layui.table,
        $ = layui.jquery;

    // 日期选择
    laydate.render({
        elem: '#ReturnDate',
        type: 'date'
    });

    // 雪花ID生成函数
    function generateSnowflakeId() {
        var timestamp = Date.now();
        var random = Math.floor(Math.random() * 1000);
        return timestamp.toString() + random.toString().padStart(3, '0');
    }

    // 自动生成编号开关默认关闭
    $('#autoGenerateReturnOrderCode').prop('checked', false);
    $('#returnOrderCodeInput').prop('readonly', false);
    form.render('checkbox');

    // 监听自动生成编号开关
    form.on('switch(autoGenerateReturnOrderCode)', function(data){
        if(data.elem.checked){
            var id = generateSnowflakeId();
            $('#returnOrderCodeInput').val(id).prop('readonly', true);
        }else{
            $('#returnOrderCodeInput').val('').prop('readonly', false);
        }
    });

    // 取消按钮
    $('#cancelBtn').on('click', function(){
        window.location.href = '/ProductionSystem/ProductionManagement/ShowProductionMaterialReturnView';
    });

    // 获取url参数id
    function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]); return null;
    }
    var id = getQueryString('id');
    if(id){
        // 查询详情并回显
        $.ajax({
            url: '/ProductionSystem/ProductionManagement/GetProductionMaterialReturnById',
            type: 'get',
            data: { id: id },
            success: function(res){
                if(res && res.data){
                    form.val('updateForm', {
                        'ReturnOrderCode': res.data.returnOrderCode,
                        'ReturnOrderName': res.data.returnOrderName,
                        'ProductionWorkOrder': res.data.productionWorkOrder,
                        'ReceiveWarehouse': res.data.receiveWarehouse,
                        'ReturnDate': res.data.returnDate ? layui.util.toDateString(new Date(res.data.returnDate), 'yyyy-MM-dd') : '',
                        'Remark': res.data.remark
                    });
                    // 如果编号是自动生成的，设置只读
                    if(res.data.returnOrderCode && /^\d{16}$/.test(res.data.returnOrderCode)){
                        $('#autoGenerateReturnOrderCode').prop('checked', true);
                        $('#returnOrderCodeInput').prop('readonly', true);
                        form.render('checkbox');
                    }
                }
            }
        });
    }

    // 表单提交
    form.on('submit(saveBtn)', function(data){
        var postData = data.field;
        postData.Id = id;
        if(postData.ReturnDate){
            postData.ReturnDate = postData.ReturnDate.replace(/-/g, '/');
        }
        $.ajax({
            url: '/ProductionSystem/ProductionManagement/UpdateProductionMaterialReturn',
            type: 'POST',
            contentType: 'application/json',
            headers: { 'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val() },
            data: JSON.stringify(postData),
            success: function(res){
                if(res.success){
                    layer.msg('修改成功', {icon:1, time:1000}, function(){
                        window.location.href = '/ProductionSystem/ProductionManagement/ShowProductionMaterialReturnView';
                    });
                }else{
                    layer.msg(res.message || '修改失败', {icon:2});
                }
            },
            error: function(){
                layer.msg('请求失败', {icon:2});
            }
        });
        return false;
    });

    // 工单选择弹窗
    $('#searchWorkOrder').on('click', function(){
        var dialogIndex = layer.open({
            type: 1,
            title: '工单选择',
            area: ['1000px', '600px'],
            content: $('#workOrderDialogTpl').html(),
            success: function(layero, index){
                table.render({
                    elem: $(layero).find('#workOrderTable'),
                    url: '/Prouduction/ShowProdction',
                    method: 'get',
                    page: true,
                    limit: 10,
                    cols: [[
                        {type: 'radio'},
                        {field: 'orderCode', title: '工单编码', width: 160},
                        {field: 'orderName', title: '工单名称', width: 160},
                        {field: 'orderSource', title: '工单来源', width: 120},
                        {field: 'orderNo', title: '订单编号', width: 120},
                        {field: 'productCode', title: '产品编号', width: 120},
                        {field: 'productName', title: '产品名称', width: 120},
                        {field: 'specifications', title: '规格型号', width: 120},
                        {field: 'unit', title: '单位', width: 80}
                    ]],
                    response: { statusCode: 0 },
                    parseData: function(res){
                        return {
                            code: 0,
                            msg: '',
                            count: res.count,
                            data: res.data
                        };
                    }
                });
                // 搜索
                form.on('submit(workOrderSearchBtn)', function(data){
                    table.reload('workOrderTable', {
                        where: data.field,
                        page: {curr: 1}
                    });
                    return false;
                });
                // 选择工单
                $(layero).on('click', '#selectWorkOrderBtn', function(){
                    var checkStatus = table.checkStatus('workOrderTable');
                    var row = checkStatus.data[0];
                    if(row){
                        $('#ProductionWorkOrder').val(row.orderCode);
                        layer.close(dialogIndex);
                    }else{
                        layer.msg('请选择一行');
                    }
                });
                // 关闭弹窗
                $(layero).on('click', '#closeWorkOrderDialog', function(){
                    layer.close(dialogIndex);
                });
            }
        });
    });
});
</script>
